'use strict';

import mongodbHandle from "src/handle/mongodbHandle";



class UserDao {
    handle: any
    constructor(db) {
        this.handle = db.collection("user")
        this.handle.createIndex("name", 1)
        this.handle.createIndex("pwd", 1)
    }

    newAndSave = async (username, password, iphone): Promise<any> => {
        let date = new Date().getTime()
        let id = await mongodbHandle.countersDao.getNextSequenceValue('user')
        return await this.handle.insertOne({
            id: id,
            name: username,
            pwd: password,
            registerTime: date,
            loginTime: date,
            serverID: 0, //最近登录的服务器
            iphone: iphone || false
        });
    }

    findOne = async (query): Promise<any> => {
        return await this.handle.findOne(query)
    }

    find = async (query): Promise<any[]> => {
        return await this.handle.find(query).toArray()
    }

    findByPage = async (query, start: number, size: number): Promise<any[]> => {
        return await this.handle.find(query).skip(start).limit(size).toArray()
    }

    findByPageAndSort = async (query, sort, start, size): Promise<any[]> => {
        return await this.handle.find(query).sort(sort).skip(start).limit(size).toArray()
    }
    //opts  { multi: true}
    updateMany = async (query, data): Promise<any> => {
        return await this.handle.updateMany(query, data);
    }

    updateOne = async (query, data): Promise<any> => {
        return await this.handle.updateOne(query, data);
    }

    count = async (query): Promise<number> => {
        return await this.handle.countDocuments(query)
    }

    remove = async (query): Promise<any> => {
        return await this.handle.remove(query, {
            multi: true
        });
    }
}

export default UserDao